package com.shisan.tingshu.payment.api;

import com.shisan.tingshu.common.login.annotation.TingshuLogin;
import com.shisan.tingshu.common.result.Result;
import com.shisan.tingshu.payment.service.WxPayService;
import com.wechat.pay.java.service.payments.model.Transaction;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Tag(name = "微信支付接口")
@RestController
@RequestMapping("api/payment/wxPay")
@Slf4j
public class WxPayApiController {

    @Autowired
    private WxPayService wxPayService;

    @PostMapping("/createJsapi/{wxPayItemType}/{orderNo}")
    @Operation(summary = "预支付下单")  // 调用后用户可以看到微信的支付二维码
    @TingshuLogin
    public Result createJsapi(@PathVariable(value = "wxPayItemType") String wxPayItemType,
                              @PathVariable(value = "orderNo") String orderNo) {

        Map<String, Object> map = wxPayService.createJsapi(wxPayItemType, orderNo);
        return Result.ok(map);
    }

    @PostMapping("/notify")
    @Operation(summary = "异步通知支付结果")  // 支付成功后微信会调用这个接口，通知支付结果
    public Map asyncNotify(HttpServletRequest httpServletRequest) {

        System.out.println("微信支付异步通知支付结果");
        HashMap<String, Object> map = new HashMap<>();
        // Transaction：微信支付平台封状好的数据结果对象
        Transaction transaction = wxPayService.asyncNotify(httpServletRequest);
        if (transaction != null && transaction.getTradeState().equals(Transaction.TradeStateEnum.SUCCESS)) {
            wxPayService.paySuccess(transaction.getOutTradeNo(), transaction);
            map.put("code", "SUCCESS");
            map.put("message", "成功");
            return map;
        }
        map.put("code", "FAIL");
        map.put("message", "失败");
        return map;
    }
}
